import { _decorator, Button, Component, EditBox, instantiate, Label, Node, path, UITransform, Vec3 } from 'cc';
import { UICtrl } from '../../Framework/Managers/UICtrl';
import { UIMgr } from '../../Framework/Managers/UIMgr';
import { Boss_Ctrl } from './GamePage/Boss_Ctrl';
import { Player_Ctrl } from './GamePage/Player_Ctrl';
import { Globle } from '../../Framework/Utils/Globle';
import { WSCmd } from '../../Framework/Utils/ws/wsCmd';
import WebSocketManager from '../../Framework/Utils/ws/WebSocketManager';
import { Room_Ctrl } from './GamePage/Room_Ctrl';
import { EventMgr } from '../../Framework/Managers/EventMgr';
import { Door_Ctrl } from './GamePage/Door_Ctrl';
import { ResMgr } from '../../Framework/Managers/ResMgr';
import { TipDialog_Ctrl } from './GamePage/TipDialog_Ctrl';
const { ccclass, property } = _decorator;

@ccclass('GamePage_Ctrl')
export class GamePage_Ctrl extends UICtrl {

    private map:Node;
    private timeGroup:Node;
    private countDownLab:Label;
    private bossPos:Node;
    private playerPos:UITransform;
    private playerAndBossGroup:Node;
    
    private allRoomData = {};
    private interval:number;
    private _countDown: number = 60;
    public get countDown(): number {
        return this._countDown;
    }
    public set countDown(value: number) {
        if (value<0) value = 0;
        this._countDown = value;
        if (this.countDownLab) {
            this.countDownLab.string = ""+this._countDown;
        }
    }
    private bossNode:Node;
    private bossSp:Boss_Ctrl;
    private isCanTouch:boolean = true;
    /**选中的房间ID */
    private selectRoomId:number = -1;
    /**房间内玩家数据 */
    private roomPlayers:any[]=[];
    /**游戏结束数据 */
    private overData:any;
    /**所有玩家角色的脚本 */
    private allPlayerSp = {};

    private tipDialog:TipDialog_Ctrl;
    private frontDoor:Door_Ctrl;
    
    onLoad(): void {
        super.onLoad();
        this.map = this.getChildOrComponent("BG/MapPrefab/Map");
        this.timeGroup = this.getChildOrComponent("BG/KillCountDown");
        this.countDownLab = this.getChildOrComponent("BG/KillCountDown/Bg/TimeGroup/CountDownLabel",Label);
        this.bossPos = this.getChildOrComponent("BG/MapPrefab/BossSpawnPoint");
        this.playerPos = this.getChildOrComponent("BG/MapPrefab/PlayerSpawnPoint",UITransform);
        this.playerAndBossGroup = this.getChildOrComponent("BG/MapPrefab/PlayerAndBossGroup");
        this.frontDoor = this.getChildOrComponent("BG/MapPrefab/FrontDoor",Door_Ctrl);
        this.AddMessage(WSCmd.ENTER_ROOM_NOTIFY);
        this.AddMessage(WSCmd.LEAVE_ROOM_NOTIFY);
        this.AddMessage(WSCmd.JPIN_SMALL_ROOM);
        this.AddMessage(WSCmd.ROUND_OVER_NOtIFY);
        this.AddMessage(WSCmd.ROUND_RESET_NOTIFY);
        this.AddMessage("SelectRoom");
        this.AddMessage("OpenKillRoomDoor");
        this.init();
    }

    init(){
        for (let i = 0; i < this.map.children.length; i++) {
            let roomSp:Room_Ctrl = this.map.children[i].getComponent(Room_Ctrl);
            roomSp.roomId = i;
            this.allRoomData[i] = {
                roomSp:roomSp
            };
        }
        this.interval = setInterval(()=>{
            this.countDown --;
        },1000);
    }
    /**重置游戏 */
    resetGame(data){
        console.log("重置事游戏数据",data)
        this.countDown = data.leftTime;
        this.timeGroup.active = true;
        this.isCanTouch = true;
        this.selectRoomId = -1;
        Globle.isCanSelect = true;
        EventMgr.Instance.Emit("SelectRoom",-1);
        if (this.tipDialog !=null) {
            this.tipDialog.closePage();
            this.tipDialog = null;
        }
        this.joinRoomCreatePlayer(data.playerData);
        for (const key in this.allRoomData) {
            this.allRoomData[key].roomSp.setDoorState(1);
        }
        this.frontDoor.openDoor();
        for (const key in this.allPlayerSp) {
            if (this.allPlayerSp[key].roomId>=0) {
                this.allPlayerSp[key].roomId = -1;
                this.allPlayerSp[key].exit(this.playerPos);
            }
        }
    }
    /**新用户加入房间 */
    enterRoomNotify(data){
        this.countDown = data.leftTime;
        this.timeGroup.active = data.roomWaiting;
        this.isCanTouch = data.roomWaiting;
        Globle.isCanSelect = data.roomWaiting;
        this.joinRoomCreatePlayer(data.playerData);
    }
    /**加入房间判断id并创建新角色 */
    joinRoomCreatePlayer(playerData){
        for (let i = 0; i < playerData.length; i++) {
            let isHave = false;
            let player = playerData[i];
            for (let j = 0; j < this.roomPlayers.length; j++) {
                if (player.id == this.roomPlayers[j].id) isHave = true;
            }
            if (!isHave) {
                this.roomPlayers.push(player)
                this.createPlayer(player);
            }
        }
    }
    
    private killRoomId:number;
    createBoss(){
        if (!this.killRoomId) return;
        if (this.killRoomId>7) return;
        let bossPath = this.allRoomData[this.killRoomId].roomSp.getRoomPathByBoss();
        if (!this.bossNode) {
            let uiPrefab = ResMgr.Instance.getAsset("GUI", "UIPrefabs/Boss");
            this.bossNode = instantiate(uiPrefab) as Node;
            this.playerAndBossGroup.addChild(this.bossNode);
            this.bossSp = this.bossNode.getComponent(Boss_Ctrl);
        }
        this.bossNode.position = this.bossPos.position;
        this.bossSp.init(bossPath);
        this.bossSp.overFun = this.bossMoveOver.bind(this);
    }
    
    bossMoveOver(){
        this.bossSp.playerImg.animation = "cikehuidao";
        this.scheduleOnce(()=>{
            this.bossSp.bossExit(this.bossPos.position);
            for (const key in this.allPlayerSp) {
                if (this.allPlayerSp[key].roomId == this.killRoomId) {
                    this.removePlayerById(key);
                }
            }
        },1);
        if (this.allPlayerSp[Globle.userData.id].roomId !=-1) { //判断是否原地不动，没选择房间
            this.tipDialog = UIMgr.Instance.CreatePrefab("TipDialog",new Vec3(0,0,0),this.node);
            if (this.allPlayerSp[Globle.userData.id].roomId == this.killRoomId) {
                this.tipDialog.init("lose");
            }else{
                this.tipDialog.init("win");
            }
        }
        this.scheduleOnce(()=>{
            for (const key in this.allRoomData) {
                this.allRoomData[key].roomSp.setDoorState(1);
            }
            this.frontDoor.openDoor();
            for (const key in this.allPlayerSp) {
                if (this.allPlayerSp[key].roomId>=0) {
                    this.allPlayerSp[key].roomId = -1;
                    this.allPlayerSp[key].exit(this.playerPos);
                }
            }
        },5);
    }

    playerMove(roomId,playerId){
        let movePath = this.allRoomData[roomId].roomSp.getRoomPathByPlayer();
        this.allPlayerSp[playerId].roomId = roomId;
        this.allPlayerSp[playerId].move(movePath);
    }

    createPlayer(data){
        let playPos = new Vec3(0,0,0);
        if (data.pos == -1) {
            playPos.x = Math.random()*this.playerPos.width-this.playerPos.width/2+this.playerPos.node.position.x;
            playPos.y = Math.random()*this.playerPos.height-this.playerPos.height/2+this.playerPos.node.position.y;
        }else{
            playPos = this.allRoomData[data.pos].roomSp.getRandomPosInRoom();
        }
        let playerSp:Player_Ctrl = UIMgr.Instance.CreatePrefab("Player",playPos,this.playerAndBossGroup);
        playerSp.init(data);
        this.allPlayerSp[data.id] = playerSp;
    }
  

    touchJoinBtn(){
        if (!this.isCanTouch) return;
        if (this.selectRoomId == -1) return;
        this.isCanTouch = false;
        Globle.isCanSelect = false;
        WebSocketManager.instance.joinSmallRoom(this.selectRoomId);
    }
    /**刺客出场 游戏结束 */
    gameOver(data){
        this.countDown = 0;
        this.timeGroup.active = false;
        this.killRoomId = data.killRoomId;
        let tipDialog = UIMgr.Instance.CreatePrefab("TipDialog",new Vec3(0,0,0),this.node);
        tipDialog.init("boss",{});
        //关闭所有的门
        for (const key in this.allRoomData) {
            this.allRoomData[key].roomSp.setDoorState(0);
        }
        this.frontDoor.closeDoor();
        this.scheduleOnce(()=>{
            this.createBoss();
        },2);
    }

    recvMsg(cmd:string , data:any){
        switch (cmd) {
            case WSCmd.ENTER_ROOM_NOTIFY:
                this.enterRoomNotify(data);
                break;
            case WSCmd.ROUND_OVER_NOtIFY:
                this.overData = data;
                this.gameOver(data);
                Globle.rankingData = data.thisWeekRank;
                break;
            case WSCmd.ROUND_RESET_NOTIFY:
                this.resetGame(data);
                break;
            case WSCmd.JPIN_SMALL_ROOM:
                this.playerMove(data.smallRoomId,data.id);
                break;
            case WSCmd.LEAVE_ROOM_NOTIFY:
                this.removePlayerById(data.playerId);
                break;
            case "SelectRoom":
                this.selectRoomId = data;
                break;
            case "OpenKillRoomDoor":
                this.allRoomData[this.killRoomId].roomSp.setDoorState(1);
                break;
        }
    }

    removePlayerById(id){
        if (this.allPlayerSp[id]) {
            this.allPlayerSp[id].die();
            delete this.allPlayerSp[id];
        }
        for (let i = 0; i < this.roomPlayers.length; i++) {
            if (this.roomPlayers[i].id == id) {
                this.roomPlayers.splice(i,1);
            }
        }
    }

    onDestroy(): void {
        clearInterval(this.interval);
    }
    clickRanking(){
        UIMgr.Instance.CreatePrefab("Ranking",new Vec3(0,0,0),this.node);
    }
    clickRecording(){
        UIMgr.Instance.CreatePrefab("Recording",new Vec3(0,0,0),this.node);
    }
}


